import React, { Component } from 'react'
import List from '../List/List.jsx'
import './Main.css'

export default class Main extends Component {
  state = {
    list: [
      { id: 78697890, value: '肥肥生日快乐', check: false },
      { id: 67456456, value: '胖子生日快乐', check: false },
      { id: 12334574, value: '胖婶生日快乐', check: false },
      { id: 67843532, value: '朱梦飞生日快乐', check: false },
      { id: 34523462, value: '懒牛加油', check: false }
    ],
  }
  subscriptions = []
  render() {
    return (
      <div className="Main">
        {this.state.list.map(v => (
          <List key={v.id} item={v} changeCheck={this.changeCheck} delList={this.delList} />
        ))}
      </div>
    )
  }

  componentDidMount() {
    this.subscriptions[0] = this.$pubsub.subscribe('Header_addList', (_, data) => this.addList(data)) // 消息订阅
    this.subscriptions[1] = this.$pubsub.subscribe('Footer_changeCheckAll', (_, data) => this.changeCheck(data.target, data.value)) // 消息订阅
    this.subscriptions[2] = this.$pubsub.subscribe('Footer_batchDelect', (_, data) => this.delList(data)) // 消息订阅
  }

  componentWillUnmount() {
    this.subscriptions.forEach(subscribe => {
      this.$pubsub.unsubscribe(subscribe)  //取消订阅
    });
    
  }

  addList = (value) => {
    let list = this.state.list.map(v => ({ ...v }))
    list.unshift({ id: Date.now(), value, check: false })
    this.setState({ list: list.map(v => ({...v, check: false})) })
    this.$pubsub.publish('Main_setCheckAll', false) //消息发布
  }

  /**
   * 删除任务列队
   * @param {string|number} target - ['batch' => 批量删除] [number => 单个删除的id]
   */
  delList = (target) => {
    let list = this.state.list
    if (target === 'batch') {
      list = list.filter(v => !v.check)
    } else {
      list.splice(list.findIndex(v => v.id === target), 1)
    }
    this.setState({ list: list.map(v => ({...v, check: false})) })
    this.$pubsub.publish('Main_setCheckAll', false) //消息发布
  }

  /**
   * 单个/全部勾选
   * @param {string|number} target - ['all' => 全选/取消全选] [number => 单个勾选的id]
   * @param {boolean} value  - 勾选与否
   */
  changeCheck = (target, value) => {
    let list = this.state.list.map(v => ({ ...v }))
    if (target === 'all') {
      list = list.map(v => ({ ...v, check: value }))
      this.$pubsub.publish('Main_setCheckAll', value) //消息发布

    } else {
      list[list.findIndex(v => v.id === target)].check = value
      this.$pubsub.publish('Main_setCheckAll', list.length === list.filter(v => v.check).length) //消息发布
    }
    this.setState({ list })
  }
}
